package org.ihelpuoo.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.ihelpuoo.I;
import org.ihelpuoo.io.CharInputStream;
import org.ihelpuoo.io.TextTokenReader;
import org.ihelpuoo.localize.Localize;

public class EscapeableProperties extends Properties
{

	@Override
	public synchronized void load(InputStream ins) throws IOException
	{
		TextTokenReader tr = new TextTokenReader((null == encoding ? new InputStreamReader(ins)
				: new InputStreamReader(ins,encoding)));
		String s;
		while (null != (s = tr.readLineIgnoreBlank()))
		{
			if (s.startsWith("#"))
				continue;
			int pos;
			char c = '0';
			for (pos = 0; pos < s.length(); pos++)
			{
				c = s.charAt(pos);
				if (c == '=' || c == ':')
					break;
			}
			if (c == '=')
			{
				String name = s.substring(0,pos);
				if (this.isEscaped)
					maps.put(name,Localize.convertAscii2Native(s.substring(pos + 1)));
				else
					maps.put(name,s.substring(pos + 1));
			}
			else if (c == ':')
			{
				String name = s.substring(0,pos);
				StringBuffer sb = new StringBuffer();
				sb.append(s.substring(pos + 1));
				String ss;
				while (null != (ss = tr.readLine()))
				{
					if (ss.startsWith("#"))
						break;
					sb.append(I.NEW_LINE + ss);
				}
				if (this.isEscaped)
					maps.put(name,Localize.convertAscii2Native(sb));
				else
					maps.put(name,sb.toString());
				if (null == ss)
					return;
			}
			else
			{
				maps.put(s,null);
			}
		}
	}

	private boolean	isEscaped;

	public void setEscaped(boolean isEscaped)
	{
		this.isEscaped = isEscaped;
	}

	public EscapeableProperties()
	{
		super();
		isEscaped = true;
	}

	public EscapeableProperties(InputStream ins, boolean isEscaped, String encoding)
			throws IOException
	{
		super(encoding);
		this.isEscaped = isEscaped;
		load(ins);
	}

	public EscapeableProperties(CharSequence cs, boolean isEscaped) throws IOException
	{
		this(new CharInputStream(cs),isEscaped);
	}

	public EscapeableProperties(InputStream ins, boolean isEscaped) throws IOException
	{
		this(ins,isEscaped,null);
	}

}
